<?php
/**
 * Ecart
 * 
 * This file is part of Ecart.
 * 
 * Ecart is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Ecart is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Ecart.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @category    Ecart
 * @package     Ecart_Admin
 * @copyright   Copyright 2008-2009 E-Cart LLC
 * @license     GNU Public License V3.0
 */

/**
 * 
 * @category    Ecart
 * @package     Ecart_Admin
 * @subpackage  Controller
 * @author      Ecart Core Team <core@ecartcommerce.com>
 */
class Ecart_Admin_ForgotController extends Ecart_Admin_Controller_Back
{
    public function init()
    {
        $this->_disableAcl  = true;
        $this->_disableAuth = true;
        parent::init();
    }

    protected function _generatePassword() 
    {
        mt_srand((double)microtime(1)*1000000);
        return md5(mt_rand());
    }
    
    public function registerAction()
    {
        $this->layout->disableLayout();
        $email = $this->_getParam('email', null);
        if (!$this->_request->isPost()) {
            $this->render();
            return;
        }
        if (empty($email)) {
            Ecart::message()->addError(
                Ecart::translate('admin')->__(
                    'Email address is required'
            ));
            $this->render();
            return;
        }
        if (Ecart::single('admin/user')->hasEmail($email)) {
            $hash = $this->_generatePassword();
            $link = $this->view->href('forgot') . '?hash=' . $hash;  
            $mail = new Ecart_Mail();
            $mail->setConfig(array(
                'event'   => 'forgot_password',
                'subject' => Ecart::translate('admin')->__(
                    'Forgot Your Backend Password'
                ),
                'data'    => array(
                    'link' => $link,
                    'firstname' => Ecart::single('admin/user')
                        ->getFirstnameByEmail($email),
                    'lastname' => Ecart::single('admin/user')
                        ->getLastnameByEmail($email)
                ),
                'to'      => $email,
                'from' => array('name' => Ecart::config()->core->store->owner)
            ));
            if ($mail->send()) {
                Ecart::single('admin/UserForgotPassword')->save(array(
                    'hash' => $hash,
                    'user_id' => Ecart::single('admin/user')
                        ->getIdByEmail($email)
                ));
                Ecart::message()->addSuccess(
                    Ecart::translate('admin')->__(
                        'See your mailbox to proceed'
                    )
                );
            }
        } else {
            Ecart::message()->addError(
                Ecart::translate('admin')->__(
                    'Email address was not found in our records'
                )
            );
        }
        $this->render();
    }

    public function indexAction()
    {
        $this->layout->disableLayout();
        $hash = $this->_getParam('hash', null);
        $this->view->hash = $hash;
        if (!$username = Ecart::single('admin/UserForgotPassword')
            ->getUserNameByHash($hash)) {

            $this->_redirect('/');
            return;
            
        }
        $this->view->username = $username; 
        $this->render();
    }
    
    public function confirmAction()
    {
        $data = $this->_getAllParams();
        if (empty($data['password'])) {
            Ecart::message()->addError(
                Ecart::translate('admin')->__(
                    'Password is required'
            ));
            $this->_forward(
                'index', null, null, array('hash' => $data['hash'])
            );
            return;
        }
        if ($data['password'] != $data['password_confirm']) {
            Ecart::message()->addError(
                Ecart::translate('admin')->__(
                    'Password confirmation does not match'
            ));
            $this->_forward(
                'index', null, null, array('hash' => $data['hash'])
            );
            return;
        }
        if (!Ecart::single('admin/userForgotPassword')
                ->isValid($data['hash'], $data['username'])) {

            Ecart::message()->addError(
               Ecart::translate('admin')->__(
                   "Invalid hash recieved. Please fill forgot form again"
            ));
            $this->_redirect('forgot/register');
            return;
        }
            
        Ecart::single('admin/user')->update(array(
            'password' => md5($data['password'])), 
            $this->db->quoteInto('username = ?', $data['username'])
        );
        Ecart::single('admin/userForgotPassword')->delete(
            $this->db->quoteInto('hash = ?', $data['hash']) 
        );
        Ecart::message()->addSuccess(
            Ecart::translate('admin')->__(
                "Password successfully changed"
        ));
        $this->_redirect('auth');
    }
    
}
